<?php

namespace App\Http\Controllers\Api;

use App\Models\Area;
use App\Models\Banner;
use App\Models\Book;
use App\Models\Cart;
use App\Models\ExpressFeeConfig;
use App\Models\Order;
use App\Models\OrderExpressInfo;
use App\Models\OrderItem;
use App\Models\User;
use App\Models\UserAccountRecord;
use App\Models\UserAddress;
use App\Models\UserCoupon;
use App\Models\UserFavoriteTag;
use App\Services\UserCouponService;
use Illuminate\Http\Request;
use DB;
use EasyWeChat;

class OrderController extends BaseController
{
    public function expressFee()
    {
        $expressFeeModel = new ExpressFeeConfig();
        $result = $expressFeeModel->getInfo();
        return $this->ok($result);
    }

    public function store(Request $request)
    {
        $address_id     = intval($request->get('address_id'));
        $pay_type       = intval($request->get('pay_type',1));
        $items          = trim($request->get('items'));//[{"book_id":10,"type":1},{"book_id":10,"type":1}]
        $user_coupon_id = intval($request->get('user_coupon_id'));

        if(empty($address_id) || empty($pay_type) || !in_array($pay_type,[1,2]) || empty($items))
        {
            return $this->err(1,200,'','参数错误');
        }

        $items = json_decode($items,true);
        if(empty($items) || !is_array($items))
        {
            return $this->err(1,200,'','参数错误');
        }

        $address = UserAddress::query()->where('id',$address_id)->first();
        if(empty($address) || $address->user_id != $this->user_id || $address->deleted)
        {
            return $this->err(1,200,'','收货地址有误');
        }

        $bookModel = new Book();

        $book_price = 0; //图书总价
        $amount = 0;
        foreach ($items as $item)
        {
            $book_price_one = 0;
            $book = $bookModel->getBookInfo($item['book_id']);
            if(empty($book))
            {
                return $this->err(1,200,'','图书不存在');
            }

            if($book['total_stock'] <= 0)
            {
                return $this->err(1,200,'','库存不足');
            }

            if($item['type'] == 1)
            {
                if($book['new_book_stock'] <= 0)
                {
                    return $this->err(1,200,'','库存不足');
                }
                $book_price_one = $book['new_book_price'];
            }
            elseif($item['type'] == 2)
            {
                if($book['good_book_stock'] <= 0)
                {
                    return $this->err(1,200,'','库存不足');
                }
                $book_price_one = $book['good_book_price'];
            }
            elseif($item['type'] == 3)
            {
                if($book['medium_book_stock'] <= 0)
                {
                    return $this->err(1,200,'','库存不足');
                }
                $book_price_one = $book['medium_book_price'];
            }
            elseif($item['type'] == 4)
            {
                if($book['medium_book_stock2'] <= 0)
                {
                    return $this->err(1,200,'','库存不足');
                }
                $book_price_one = $book['medium_book_price2'];
            }
            elseif($item['type'] == 5)
            {
                if($book['medium_book_stock3'] <= 0)
                {
                    return $this->err(1,200,'','库存不足');
                }
                $book_price_one = $book['medium_book_price3'];
            }
            elseif($item['type'] == 6)
            {
                if($book['medium_book_stock4'] <= 0)
                {
                    return $this->err(1,200,'','库存不足');
                }
                $book_price_one = $book['medium_book_price4'];
            }
            elseif($item['type'] == 7)
            {
                if($book['medium_book_stock5'] <= 0)
                {
                    return $this->err(1,200,'','库存不足');
                }
                $book_price_one = $book['medium_book_price5'];
            }
            elseif($item['type'] == 8)
            {
                if($book['medium_book_stock6'] <= 0)
                {
                    return $this->err(1,200,'','库存不足');
                }
                $book_price_one = $book['medium_book_price6'];
            }

            $book_price += $book_price_one*1;
            $amount++;
        }

        $province = Area::query()->where('id',$address->province_id)->first();
        $is_far = 0;
        if(!empty($province) && $province->is_far == 1)
        {
            //偏远地区
            $is_far = 1;
        }

        //dd($province);
        $expressFeeModel = new ExpressFeeConfig();
        $expressFee = $expressFeeModel->getInfo();

        $express_fee         = $expressFee['unfar_express_fee'];  //运费
        $express_order_price = $expressFee['unfar_order_price'];  //满多少免邮
        if($is_far)
        {
            $express_fee         = $expressFee['far_express_fee'];  //运费
            $express_order_price = $expressFee['far_order_price'];  //满多少免邮
        }

        //计算运费
        $fee_price = $express_fee;
        if($book_price >= $express_order_price)
        {
            $fee_price = 0;
        }

        $coupon_decr_price = 0; //红包减免金额
        $coupon_id = 0;
        if($user_coupon_id)
        {
            $user_coupon = UserCoupon::query()->where('id',$user_coupon_id)->where('expired_at','>',$this->time)->where('state',0)->first();
            if(empty($user_coupon))
            {
                return $this->err(1,200,'','红包没法使用');
            }
            if($book_price >= $user_coupon->coupon_order_price)
            {
                $coupon_decr_price = $user_coupon->coupon_amount;
            }

        }


        $user = User::query()->select(['id','account','wechat_openid','unionid','wechat_nickname'])->where('id',$this->user_id)->first();


        $account_decr_price = 0;//余额支付减免金额
        $price = $fee_price + $book_price - $coupon_decr_price;
        if($pay_type == 1)
        {
            $account_decr_price = round($book_price*0.13,1);
            //$account_decr_price = $book_price - round($book_price*0.87,2);
            $price = $price - $account_decr_price;

            if($user->account < $price)
            {
                return $this->err(1,200,'','账户余额不足');
            }
        }

        $price = round($price,1);
        DB::beginTransaction();    //主事务
        try {
            // 创建一个订单
            $order = new Order([
                'price'                 => $price,
                'book_price'            => round($book_price,1),
                'fee_price'             => round($fee_price,1),
                'coupon_id'             => $coupon_id,
                'user_coupon_id'        => $user_coupon_id,
                'coupon_decr_price'     => round($coupon_decr_price,1),
                'account_decr_price'    => round($account_decr_price,1),
                'pay_type'              => $pay_type,
                'created_at'            => $this->time,
                'updated_at'            => $this->time,
                'state'                 => 0,
                'address_id'            => $address_id,
                'address_receiver'      => $address->receiver,
                'address_mobile'        => $address->mobile,
                'address_province_id'   => $address->province_id,
                'address_city_id'       => $address->city_id,
                'address_area_id'       => $address->area_id,
                'address_province_name' => $address->province_name,
                'address_city_name'     => $address->city_name,
                'address_area_name'     => $address->area_name,
                'address'               => $address->address,
                'amount'                => $amount,
                'express_delivery_id'   => 'ZTO',
                'user_openid'           => $user->wechat_openid,
                'user_nickname'         => $user->wechat_nickname,
            ]);
            // 订单关联到当前用户
            $order->user()->associate($user);
            // 写入数据库
            $order->save();

            $keyword1 = '';
            $tags = [];
            $tags_arr = [];
            foreach ($items as $key=>$item)
            {
                $book = Book::find($item['book_id']);

                if(!empty($book->category_ids))
                {
                    $category_ids_arr = explode(',',$book->category_ids);
                    foreach ($category_ids_arr as $cate)
                    {
                        if(!in_array($cate,$tags))
                        {
                            $tags[] = $cate;
                            $tags_arr[] = [
                                'category_id' => $cate,
                                'category_pid'=> $book->category_pid
                            ];
                        }
                    }
                }
                if($key == 0)
                {
                    $keyword1 .= "《".$book->title."》";
                }

                if($item['type'] == 1)
                {
                    if($pay_type == 1)
                    {
                        $book->decrement('new_book_stock', 1);
                    }
                    $book_price = $book->new_book_price;
                }
                elseif($item['type'] == 2)
                {
                    if($pay_type == 1)
                    {
                        $book->decrement('good_book_stock', 1);
                    }

                    $book_price = $book->good_book_price;
                }
                elseif($item['type'] == 3)
                {
                    if($pay_type == 1)
                    {
                        $book->decrement('medium_book_stock', 1);
                    }

                    $book_price = $book->medium_book_price;
                }
                elseif($item['type'] == 4)
                {
                    if($pay_type == 1)
                    {
                        $book->decrement('medium_book_stock2', 1);
                    }

                    $book_price = $book->medium_book_price2;
                }
                elseif($item['type'] == 5)
                {
                    if($pay_type == 1)
                    {
                        $book->decrement('medium_book_stock3', 1);
                    }

                    $book_price = $book->medium_book_price3;
                }
                elseif($item['type'] == 6)
                {
                    if($pay_type == 1)
                    {
                        $book->decrement('medium_book_stock4', 1);
                    }

                    $book_price = $book->medium_book_price4;
                }
                elseif($item['type'] == 7)
                {
                    if($pay_type == 1)
                    {
                        $book->decrement('medium_book_stock5', 1);
                    }

                    $book_price = $book->medium_book_price5;
                }
                elseif($item['type'] == 8)
                {
                    if($pay_type == 1)
                    {
                        $book->decrement('medium_book_stock6', 1);
                    }

                    $book_price = $book->medium_book_price6;
                }

                if($pay_type == 1)
                {
                    //减总库存
                    $book->decreaseStock(1);
                }


                $item = $order->items()->make([
                    'book_id'     => $item['book_id'],
                    'type'        => $item['type'],
                    'amount'      => 1,
                    'price'       => $book_price,
                    'book_title'  => $book['title'],
                    'book_image'  => $book['image'],
                    'book_author' => $book['author'],
                    'user_id'     => $this->user_id,
                ]);
                $item->save();
            }

            $keyword1 .= '...共'.count($items).'本书';

            // 将下单的商品从购物车中移除
            $bookIds = collect($items)->pluck('book_id');
            //dd($bookIds);
            $user->carts()->whereIn('book_id', $bookIds)->delete();

            //红包标志使用
            if($user_coupon_id)
            {
                $user_coupon->update(['used_at'=>$this->time,'state'=>1]);
            }

            $userAddressModel = new UserAddress();
            $userAddressModel->setDefaultAddress($address_id,$this->user_id);

            $banner = Banner::query()->where('position',4)->where('is_show',1)->first();

            $banner_item = [];
            if(!empty($banner))
            {
                $banner_item = [
                    'image' => $banner->image,
                    'url'   => $banner->url,
                ];
            }

            if($pay_type == 1)
            {
                //$user->increment('buy_orders_num');

                $order->update([
                    'state' => 1,
                    'pay_at' => $this->time,
                ]);

                //减去用户账户余额
                $user->decrement('account',round($price,1));
                //账户余额记录
                UserAccountRecord::create([
                    'type'    => 1,
                    'account' => round($price,1),
                    'remark'  => '余额支付',
                    'user_id' => $this->user_id,
                ]);

                //发送推送消息
                $officialAccount = EasyWeChat::officialAccount(); // 公众号
                $wechat_user = \DB::table('wechat_users')->where('unionid',$user->unionid)->first();
                if(!empty($wechat_user))
                {
                    $openid = $wechat_user->openid;

                    $first = "您的买书订单支付成功，等待发货\r\n";
                    $keyword2 = $price.'元';
                    $officialAccount->template_message->send([
                        'touser'        => $openid,
                        'template_id'   => '4dSwqWCdFqYu5k00KxoLtX3YTdCeDB2sAbwuyk73irs',
                        'url'  => '',
                        'miniprogram' => [
                            'appid'     => config('wechat.mini_program.default.app_id'),
                            'pagepath'  => 'pages/order/order-detail/order-detail?id='.$order->id,
                        ],
                        'data' => [
                            'first'     => $first,
                            'keyword1'  => $keyword1,
                            'keyword2'  => $keyword2,
                            'keyword3'  => $address->receiver,
                            'keyword4'  => $address->province_name.$address->city_name.$address->area_name.$address->address,
                            'keyword5'  => $address->mobile."\r\n",
                            'remark'    => '我们将在24小时内为您安排发货，请耐心等待。如收货地址有误，请及时取消订单或联系客服。'
                        ],
                    ]);
                }

                DB::commit();

                $officialAccount->template_message->send([
                    'touser'        => 'oKOD01EmbGyVy9nEgrq7N6Hh-BG0',
                    'template_id'   => 'T2LwyJ_zHil6B0QfKDKfjUL19358TPQlVVoJ6reMMrU',
                    'url'  => '',
                    'miniprogram' => [
                        'appid'     => config('wechat.mini_program.default.app_id'),
                        'path'  => '',
                    ],
                    'data' => [
                        'first'     => '后台有新的购书订单,请尽快发货'."\r\n",
                        'keyword1'  => $order->no,
                        'keyword2'  => '快鱼二手书',
                        'keyword3'  => date('Y-m-d H:i:s',$this->time)."\r\n",
                        'remark'    => ''
                    ],
                ]);

                $tag_data = [];
                if(!empty($tags_arr))
                {
                    foreach ($tags_arr as $tag)
                    {
                        $tag_data[] = [
                            'user_id'       => $this->user_id,
                            'category_id'   => $tag['category_id'],
                            'category_pid'  => $tag['category_pid'],
                        ];
                    }
                }
                DB::table('user_favorite_tags')->insert($tag_data);
                return $this->ok(['order_id'=> $order->id, 'banner' => $banner_item],'下单成功');
            }
            else
            {
                // scan 方法为拉起微信扫码支付
                /*$result = app('wechat_pay')->scan([
                    'out_trade_no' => $order->no,  // 商户订单流水号，与支付宝 out_trade_no 一样
                    //'total_fee'    => $order->price * 100, // 与支付宝不同，微信支付的金额单位是分。
                    'total_fee'    => 0.01 * 100, // 与支付宝不同，微信支付的金额单位是分。
                    'body' => '支付快鱼二手书订单,订单号:'.$order->no, // 订单描述
                ]);*/

                //正式环境小程序支付
                $wechat_order = [
                    'out_trade_no' => $order->no,
                    'total_fee'    => $order->price*100, // **单位：分**
                    //'total_fee' => 0.01*100, // **单位：分**
                    'body' => '支付快鱼二手书订单,订单号:'.$order->no,
                    //'openid' => 'oykEg5WGTi181uPuJUX5jT7jlvr4',
                    'openid' => $user->wechat_openid,
                ];
                $result = app('wechat_pay')->miniapp($wechat_order);
                DB::commit();

                $tag_data = [];
                if(!empty($tags_arr))
                {
                    foreach ($tags_arr as $tag)
                    {
                        $tag_data[] = [
                            'user_id'       => $this->user_id,
                            'category_id'   => $tag['category_id'],
                            'category_pid'  => $tag['category_pid'],
                        ];
                    }
                }
                DB::table('user_favorite_tags')->insert($tag_data);

                return $this->res([
                    'data' => [
                        'pay_info'  => $result,
                        'order_id'  => $order->id,
                        'order_no'  => $order->no,
                        'banner'    => $banner_item,
                    ]
                ]);
            }


        } catch (\Exception $e) {
            DB::rollBack();
            //echo $e->getMessage();
            return $this->err(1,200,$e->getMessage(),'下单失败');
        }
    }


    public function show(Request $request)
    {
        $order_id = intval($request->get('order_id'));
        if(empty($order_id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $order = Order::query()->with(['items'])->where('id',$order_id)->first();
        if(empty($order) || $order->user_id != $this->user_id)
        {
            return $this->err(1,200,'','订单不存在');
        }


        $books = [];
        if(!empty($order->items))
        {
            foreach ($order->items as $v)
            {
                $books[] = [
                    'book_id'    => $v->book_id,
                    'type'       => $v->type,
                    'price'      => $v->price,
                    'book_title' => $v->book_title,
                    'book_image' => $v->book_image,
                ];
            }
        }

        $result = [
            'id'                    => $order->id,
            'user_id'               => $order->user_id,
            'no'                    => $order->no,
            'price'                 => $order->price,
            'book_price'            => $order->book_price,
            'fee_price'             => $order->fee_price,
            'coupon_decr_price'     => $order->coupon_decr_price,
            'account_decr_price'    => $order->account_decr_price,
            'pay_type'              => $order->pay_type,
            'pay_at'                => $order->pay_at,
            'created_at'            => $order->created_at,
            'state'                 => $order->state,
            'maybe_submit_time'     => date('m-d',strtotime("+1 day",$order->created_at)).' 18:00',
            'express_delivery_id'   => $order->express_delivery_id == 'ZTO' ? '中通物流' : '',
            'express_waybill_id'    => $order->express_waybill_id,
            'address_receiver'      => $order->address_receiver,
            'address_mobile'        => $order->address_mobile,
            'address_province_name' => $order->address_province_name,
            'address_city_name'     => $order->address_city_name,
            'address_area_name'     => $order->address_area_name,
            'address'               => $order->address,
            'amount'                => $order->amount,
            'refund_status'         => $order->refund_status,
            'books'                 => $books
        ];
        return $this->ok($result);
    }

    public function express(Request $request)
    {
        $order_id = intval($request->get('order_id'));
        if(empty($order_id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $order = Order::query()->with(['items'])->where('id',$order_id)->first();
        if(empty($order) || $order->user_id != $this->user_id)
        {
            return $this->err(1,200,'','订单不存在');
        }

        $express_info = OrderExpressInfo::query()->where('order_id',$order_id)->orderBy('id','desc')->first();


        $express_state = !empty($express_info->last_action_type) ? $express_info->last_action_type : 0;
        $express_state_str = getWechatExpressState($express_state);
        $result = [
            'id'                    => $order->id,
            'address_receiver'      => $order->address_receiver,
            'address_mobile'        => $order->address_mobile,
            'address_province_name' => $order->address_province_name,
            'address_city_name'     => $order->address_city_name,
            'address_area_name'     => $order->address_area_name,
            'address'               => $order->address,
            'express_no'            => $order->express_no,
            'express_delivery_id'   => $order->express_delivery_id == 'ZTO' ? '中通物流' : '',
            'express_state'         => $express_state,
            'express_state_str'     => $express_state_str,
            'express_items'         => !empty($express_info->path_item_list) ? json_decode($express_info->path_item_list,true) : [],
        ];
        return $this->ok($result);
    }

    public function applyRefund(Request $request)
    {
        $order_id = intval($request->get('order_id'));
        if(empty($order_id))
        {
            return $this->err(1,200,'','参数错误');
        }

        $order = Order::query()->where('id',$order_id)->first();
        if(empty($order) || $order->user_id != $this->user_id)
        {
            return $this->err(1,200,'','订单不存在');
        }

        if($order->state != 1)
        {
            return $this->err(1,200,'','状态错误,无法申请退款');
        }

        if($order->refund_status > 0)
        {
            return $this->err(1,200,'','该订单已经申请过退款，请勿重复申请');
        }

        //判断当天只能取消一次
        $day_start_time = strtotime(date('Y-m-d',$this->time). '00:00:00');
        $day_end_time = strtotime(date('Y-m-d',$this->time). '23:59:59');

        $count = Order::query()->where('user_id',$this->user_id)->where('state',-1)->where('cancel_at','>=',$day_start_time)->where('cancel_at','<=',$day_end_time)->count();
        if($count >= 1)
        {
            return $this->err(1,200,'','您今天已经取消过一次订单，所以暂时无法再次取消订单');
        }


        $user = User::find($order->user_id);
        if($order->pay_type  == 1)
        {
            DB::beginTransaction();    //主事务
            try {
                // 将订单退款状态改为退款成功
                $order->update([
                    'refund_status' => 2,
                    'updated_at'    => $this->time,
                    'state'         => -1,
                    'cancel_at'     => $this->time,
                ]);

                //减去用户账户余额
                $user->increment('account',round($order->price,1));
                //账户余额记录
                UserAccountRecord::create([
                    'type'    => 2,
                    'account' => round($order->price,1),
                    'remark'  => '订单取消',
                    'user_id' => $this->user_id,
                ]);

                $item = OrderItem::query()->with(['book'])->where('order_id',$order->id)->orderBy('id','asc')->first();
                $keyword2 = "《".$item->book->title."》...共".$order->amount.'本书';

                $officialAccount = EasyWeChat::officialAccount(); // 公众号
                $wechat_user = \DB::table('wechat_users')->where('unionid',$user->unionid)->first();
                if(!empty($wechat_user))
                {
                    $openid = $wechat_user->openid;

                    $first = "您的买书订单取消成功，已退款\r\n";
                    $officialAccount->template_message->send([
                        'touser'        => $openid,
                        'template_id'   => 'eAewZ_8ibUx3OjnQdL2WJQTXIAPC5mgMQn7iS9QXlRg',
                        'url'  => '',
                        'miniprogram' => [
                            'appid'     => config('wechat.mini_program.default.app_id'),
                            'path'  => '/pages/order/order-detail/order-detail?id='.$order->id,
                        ],
                        'data' => [
                            'first'     => $first,
                            'keyword1'  => $order->price.'元',
                            'keyword2'  => $keyword2,
                            'keyword3'  => $order->no."\r\n",
                            'remark'    => '退款将原路退回到您的支付账户，请注意查收。（微信支付退款到账时间，请以微信通知为准）'
                        ],
                    ]);
                }

                $items = OrderItem::query()->select(['book_id','order_id','type'])->where('order_id',$order->id)->get();
                foreach ($items as $v)
                {
                    $book = Book::find($v->book_id);
                    if($v->type == 1)
                    {
                        $book->increment('new_book_stock', 1);
                    }
                    elseif($v->type == 2)
                    {
                        $book->increment('good_book_stock', 1);
                    }
                    elseif($v->type == 3)
                    {
                        $book->increment('medium_book_stock', 1);
                    }
                    elseif($v->type == 4)
                    {
                        $book->increment('medium_book_stock2', 1);
                    }
                    elseif($v->type == 5)
                    {
                        $book->increment('medium_book_stock3', 1);
                    }
                    elseif($v->type == 6)
                    {
                        $book->increment('medium_book_stock4', 1);
                    }
                    elseif($v->type == 7)
                    {
                        $book->increment('medium_book_stock5', 1);
                    }
                    elseif($v->type == 8)
                    {
                        $book->increment('medium_book_stock6', 1);
                    }

                    //加总库存
                    $book->addStock(1);
                }

                DB::commit();
                return $this->ok([],'订单取消成功');
            } catch (\Exception $e) {
                DB::rollBack();
                //echo $e->getMessage();
                return $this->err(1,200,$e->getMessage(),'申请退款失败');
            }
        }
        else
        {
            DB::beginTransaction();    //主事务
            try {
                // 将订单退款状态改为已申请退款
                $order->update([
                    'refund_status' => 1,
                    'updated_at'    => $this->time,
                ]);

                // 生成退款订单号
                $refundNo = Order::findAvailableNo();
                app('wechat_pay')->refund([
                    'out_trade_no'  => $order->no, // 之前的订单流水号
                    'total_fee'     => $order->price * 100, //原订单金额，单位分
                    'refund_fee'    => $order->price * 100, // 要退款的订单金额，单位分
                    //'total_fee'     => 0.01 * 100, //原订单金额，单位分
                    //'refund_fee'    => 0.01 * 100, // 要退款的订单金额，单位分
                    'out_refund_no' => $refundNo, // 退款订单号
                    // 微信支付的退款结果并不是实时返回的，而是通过退款回调来通知，因此这里需要配上退款回调接口地址
                    //'notify_url' => 'https://requestbin.leo108.com/q58ubpq5' // 由于是开发环境，需要配成 requestbin 地址
                    'notify_url' => route('payment.wechat.refund_notify'),
                ]);

                DB::commit();
                return $this->ok([]);
            } catch (\Exception $e) {
                DB::rollBack();
                //echo $e->getMessage();
                return $this->err(1,200,$e->getMessage(),'申请退款失败');
            }
        }
    }

    public function index(Request $request)
    {
        $page      = intval($request->get('page',1));
        $page      = max($page ,1);
        $page_size = intval($request->get('page_size',10));

        $builder = Order::query()->with(['items'])->where('user_id',$this->user_id)->where('state','!=',0);

        $columns = ['id','created_at','state','amount','price','no'];
        $list = $builder->orderBy('id','desc')->paginate($page_size,$columns,'page',$page);

        $items = [];
        if(!empty($list->items()))
        {
            foreach ($list->items() as $item)
            {
                $items[] = [
                    'id'          => $item->id,
                    'created_at'  => $item->created_at,
                    'state'       => $item->state,
                    'amount'      => $item->amount,
                    'price'       => $item->price,
                    'no'          => $item->no,
                    'items'       => $item->items,
                ];
            }
        }


        $total_books = Order::query()->where('user_id',$this->user_id)->where('state','!=',0)->sum('amount');

        $data = [
            '_meta' => [
                'total_count'  => $list->total(),
                'page_count'   => $list->lastPage(),
                'current_page' => $list->currentPage(),
                'per_page'     => $list->perPage()
            ],
            "items"         => $items,
            'total_books'   => $total_books,
        ];

        return $this->res([
            'data' => $data
        ]);
    }

    public function submit(Request $request)
    {
        $ids = trim($request->get('ids'));
        $address_id = intval($request->get('address_id'));

        if(empty($ids))
        {
            return $this->err(1,200,'','参数错误');
        }

        $books = [];
        $bookModel = new Book();
        $book_price = 0; //图书总价
        $amount = 0;

        $ids_arr = explode(',',$ids);
        if(!empty($ids_arr))
        {
            foreach ($ids_arr as $v)
            {
                $book_price_one = 0;
                $row = Cart::query()->where('id',$v)->first();

                $book = $bookModel->getBookInfo($row->book_id);
                if(empty($book))
                {
                    return $this->err(1,200,'','图书不存在');
                }

                if($book['total_stock'] <= 0)
                {
                    return $this->err(1,200,'',$book['title'].'库存不足');
                }

                if($row->type == 1)
                {
                    if($book['new_book_stock'] <= 0)
                    {
                        return $this->err(1,200,'',$book['title'].'库存不足');
                    }
                    $book_price_one = $book['new_book_price'];
                }
                elseif($row->type == 2)
                {
                    if($book['good_book_stock'] <= 0)
                    {
                        return $this->err(1,200,'',$book['title'].'库存不足');
                    }
                    $book_price_one = $book['good_book_price'];
                }
                elseif($row->type == 3)
                {
                    if($book['medium_book_stock'] <= 0)
                    {
                        return $this->err(1,200,'',$book['title'].'库存不足');
                    }
                    $book_price_one = $book['medium_book_price'];
                }
                elseif($row->type == 4)
                {
                    if($book['medium_book_stock2'] <= 0)
                    {
                        return $this->err(1,200,'',$book['title'].'库存不足');
                    }
                    $book_price_one = $book['medium_book_price2'];
                }
                elseif($row->type == 5)
                {
                    if($book['medium_book_stock3'] <= 0)
                    {
                        return $this->err(1,200,'',$book['title'].'库存不足');
                    }
                    $book_price_one = $book['medium_book_price3'];
                }
                elseif($row->type == 6)
                {
                    if($book['medium_book_stock4'] <= 0)
                    {
                        return $this->err(1,200,'',$book['title'].'库存不足');
                    }
                    $book_price_one = $book['medium_book_price4'];
                }
                elseif($row->type == 7)
                {
                    if($book['medium_book_stock5'] <= 0)
                    {
                        return $this->err(1,200,'',$book['title'].'库存不足');
                    }
                    $book_price_one = $book['medium_book_price5'];
                }
                elseif($row->type == 8)
                {
                    if($book['medium_book_stock6'] <= 0)
                    {
                        return $this->err(1,200,'',$book['title'].'库存不足');
                    }
                    $book_price_one = $book['medium_book_price6'];
                }
                $book_price += $book_price_one*1;
                $amount++;

                $books[] = [
                    'type'              => $row->type,
                    'book_id'           => $book['id'],
                    'title'             => $book['title'],
                    'image'             => $book['image'],
                    'new_book_price'    => $book['new_book_price'],
                    'new_book_stock'    => $book['new_book_stock'],
                    'good_book_price'   => $book['good_book_price'],
                    'good_book_stock'   => $book['good_book_stock'],
                    'medium_book_price' => $book['medium_book_price'],
                    'medium_book_stock' => $book['medium_book_stock'],
                    'medium_book_price2' => $book['medium_book_price2'],
                    'medium_book_stock2' => $book['medium_book_stock2'],
                    'medium_book_price3' => $book['medium_book_price3'],
                    'medium_book_stock3' => $book['medium_book_stock3'],
                    'medium_book_price4' => $book['medium_book_price4'],
                    'medium_book_stock4' => $book['medium_book_stock4'],
                    'medium_book_price5' => $book['medium_book_price5'],
                    'medium_book_stock5' => $book['medium_book_stock5'],
                    'medium_book_price6' => $book['medium_book_price6'],
                    'medium_book_stock6' => $book['medium_book_stock6'],
                ];
            }
        }

        //获取默认收货地址
        $is_far = 0;
        if(!empty($address_id))
        {
            $address = UserAddress::query()->where('id',$address_id)->where('user_id',$this->user_id)->where('deleted',0)->first();
        }
        else
        {
            $address = UserAddress::query()->where('deleted',0)->where('user_id',$this->user_id)->where('is_default',1)->first();
        }

        if(!empty($address))
        {
            $province = Area::query()->where('id',$address->province_id)->first();
            if(!empty($province) && $province->is_far == 1)
            {
                //偏远地区
                $is_far = 1;
            }
        }

        $expressFeeModel = new ExpressFeeConfig();
        $expressFee = $expressFeeModel->getInfo();

        $express_fee         = $expressFee['unfar_express_fee'];  //运费
        $express_order_price = $expressFee['unfar_order_price'];  //满多少免邮
        if($is_far)
        {
            $express_fee         = $expressFee['far_express_fee'];  //运费
            $express_order_price = $expressFee['far_order_price'];  //满多少免邮
        }

        //计算运费
        $fee_price = $express_fee;
        if($book_price >= $express_order_price)
        {
            $fee_price = 0;
        }

        $userCouponService = new UserCouponService();
        $coupons = $userCouponService->getOrderCoupons($this->user_id,$book_price);


        $result = [
            'address'       => $address ? $address : (object)null,
            'books'         => $books,
            'fee_price'     => round($fee_price,1),
            'book_price'    => round($book_price,1),
            'coupons'       => $coupons,
        ];
        return $this->ok($result);
    }

    public function coupons(Request $request)
    {
        $items  = trim($request->get('items'));//[{"book_id":10,"type":1},{"book_id":10,"type":1}]
        if(empty($items))
        {
            return $this->err(1,200,'','参数错误');
        }

        $items = json_decode($items,true);
        if(empty($items) || !is_array($items))
        {
            return $this->err(1,200,'','参数错误');
        }

        $bookModel = new Book();

        $book_price = 0; //图书总价
        foreach ($items as $item)
        {
            $book = $bookModel->getBookInfo($item['book_id']);
            if(empty($book))
            {
                return $this->err(1,200,'','图书不存在');
            }

            if($book['total_stock'] <= 0)
            {
                return $this->err(1,200,'','库存不足');
            }

            if($item['type'] == 1)
            {
                if($book['new_book_stock'] <= 0)
                {
                    return $this->err(1,200,'','库存不足');
                }
                $book_price = $book['new_book_price'];
            }
            elseif($item['type'] == 2)
            {
                if($book['good_book_stock'] <= 0)
                {
                    return $this->err(1,200,'','库存不足');
                }
                $book_price = $book['good_book_price'];
            }
            elseif($item['type'] == 3)
            {
                if($book['medium_book_stock'] <= 0)
                {
                    return $this->err(1,200,'','库存不足');
                }
                $book_price = $book['medium_book_price'];
            }

            $book_price += $book_price*1;
        }

        $userCouponService = new UserCouponService();
        $ret = $userCouponService->getOrderCoupons($this->user_id,$book_price);
        return $this->ok($ret);
    }
}
